package com.ljf.common.core;

import com.ljf.common.exception.ServiceException;
import com.ljf.common.result.ResultModel;
import com.ljf.common.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常捕获
 *
 * @author LJF
 * @since 2024-01-23
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(value = ServiceException.class)
    public ResultModel exceptionHandler(ServiceException e){
        logger.error("业务异常", e);
        return ResultUtil.fail(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = NullPointerException.class)
    public ResultModel exceptionHandler(NullPointerException e){
        logger.error("空指针异常", e);
        return ResultUtil.fail("服务异常：空指针, 请联系管理员");
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResultModel exceptionHandler(Exception e){
        logger.error("异常", e);
        return ResultUtil.fail("系统异常, 请联系管理员");
    }

    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public ResultModel exceptionHandler(BindException e){
        logger.error("参数异常", e);
        return ResultUtil.fail("参数异常");
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultModel exceptionHandler(MethodArgumentNotValidException e){
        logger.error("异常", e);
        StringBuilder msg = new StringBuilder();
        for (ObjectError allError : e.getBindingResult().getAllErrors()) {
            msg.append(allError.getDefaultMessage()).append("; ");
        }
        return ResultUtil.fail(msg.toString());
    }

}
